﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using System.Data.Linq;
using System.Text;
using DataLayer;

namespace DALConsoleTest
{
	class Tests
	{
		private DAL dal;
		private int[,] newMaze;

		public Tests()
		{
			dal = new DAL();
			newMaze = new int[/*mrow*/4,/*mcol*/ 4] {
			{ 1,1,1,1},
			{ 1,2,1,0},
			{ 1,0,1,0},
			{ 1,0,1,0}
			};           
			
			
		}

        public void force(string sql)
        {
            try
            {
                dal.ExecuteCommand(sql);
            }
            catch { }
            finally { }
            
        }


        public void db_del_lev(String l_name)
        {
            int l_id = dal.ExecuteQuery<int>("SELECT l_id FROM LEVELS WHERE l_name = '{0}'", l_name).FirstOrDefault();
            dal.ExecuteCommand("DELETE FROM LEVEL_STRUCT WHERE l_id ={0}", l_id);
            dal.ExecuteCommand("DELETE FROM LEVELS WHERE l_name = '{0}'", l_name);
        }


        public void db_tabledrop()
        {    
            this.force("DROP TABLE LEVEL_STRUCT");
            this.force("DROP TABLE LEVELS");
        }


        public void db_CREATETABLE()
        {
            dal.ExecuteCommand("CREATE TABLE LEVELS (l_name char(40), l_row_size int, l_col_size int, l_id int PRIMARY KEY NOT NULL identity(1,1))");
            dal.ExecuteCommand("CREATE TABLE LEVEL_STRUCT (l_id int NOT NULL, l_row int, l_col int, l_val int, primary key(l_id, l_row, l_col), Foreign Key (l_id) references LEVELS(l_id))");
        }



        //      <<--- !!!    OK OK OK OK finna út afhverju l_name fær alltaf strenginn @p0 !!!! OK
        //




        // db_write:
        // 
		//      Fylkið newMaze inniheldur völundarhús.
		//
		//      db_write les hvern column fyrir sig inn í LEVEL_STRUCT töfluna í SQL fyrirspurnarmáli.
		//
		//      Aðferðin tekur inn l_name (nafni borðsins)  og
		//                         l_id  (kennitala borðsins)
		//
		public void db_write(String l_name)
		{
            int r_size = this.newMaze.GetUpperBound(0) +1; //stærð fylkis rows
            int c_size = this.newMaze.GetUpperBound(1) +1; //stærð fylkis columns

            //Eftirfarandi eru köll í SQL þjóninn. Töflurnar LEVELS og LEVEL_STRUCT eru búnar til.

			dal.ExecuteCommand("INSERT INTO LEVELS(l_name, l_row_size, l_col_size) values ('{0}', {1}, {2})", l_name, r_size, c_size); // <- verð að passa að 0 breytist
            int l_id = dal.ExecuteQuery<int>("SELECT l_id FROM LEVELS WHERE l_name = '{0}'", l_name).FirstOrDefault();
      		
            //Þessi forlykkja setur hvert hnit fylkisins inn í töfluna LEVEL_STRUCT sem er svo tengd með lykli í LEVELS

            for (int i = 0; i < r_size; i++)
			{
				for (int j = 0; j < c_size ; j++)
				{
					dal.ExecuteCommand(String.Format("INSERT into LEVEL_STRUCT(l_row, l_col, l_val, l_id) values({0}, {1}, {2}, {3})", i, j, newMaze[i,j], l_id ));
					
				}
			}    
		}



		// db_read les SQL kóða og notar l_name sem leitarstreng.
		// loks eru gögnin skrifuð inn í newMaze fylkið.   <- sem verður síðan loadað í nýtt borð.

		public void db_read(String l_name)
		{
			int r_size = dal.ExecuteQuery<int>("SELECT l_row_size FROM LEVELS WHERE l_name = '{0}'", l_name).FirstOrDefault();
			int c_size = dal.ExecuteQuery<int>("SELECT l_col_size FROM LEVELS WHERE l_name = '{0}'", l_name).FirstOrDefault();
            int l_id = dal.ExecuteQuery<int>("SELECT l_id FROM LEVELS WHERE l_name = '{0}'", l_name).FirstOrDefault();

			for (int i = 0; i < r_size; i++)
			{
				for (int j = 0; j < c_size; j++)
				{
				newMaze[i,j] = dal.ExecuteQuery<int>("SELECT l_val FROM LEVEL_STRUCT WHERE l_id = {0} AND l_row = {1} AND l_col = {2}", l_id, i, j).FirstOrDefault();
				}
			}
		}


        // PRINTOUTLOUD: 
        //
        //      prufuaðferð sem "testar" að prenta 'level' úr gagnagrunni, í console, ef nafn borðsins
        //      er sett inn í aðferðina.
        //
        public void PRINTOUTLOUD(String l_name)
        {
            int r_size = dal.ExecuteQuery<int>("SELECT l_row_size FROM LEVELS WHERE l_name = '{0}'", l_name).FirstOrDefault();
            int c_size = dal.ExecuteQuery<int>("SELECT l_col_size FROM LEVELS WHERE l_name = '{0}'", l_name).FirstOrDefault();
            
            for (int i = 0; i < r_size; i++)
            {
                Console.WriteLine();
                for (int j = 0; j < c_size; j++)
                {
                    Console.Write(newMaze[i,j]);
           
                }
             
            }
            Console.ReadLine();
        }


	}


	/// <summary>
	/// Used to test DataLayer directly!
	/// </summary>
	class Program
	{
		static void Main(string[] args)
		{
			Tests tests = new Tests();
            String levelname = "Test level1";
            String levelname2 = "Test level2";
            tests.db_tabledrop();
            tests.db_CREATETABLE();
            tests.db_write(levelname);
            tests.db_write(levelname2);
            tests.db_read(levelname);
            tests.db_read(levelname2);
            tests.PRINTOUTLOUD(levelname);
            tests.PRINTOUTLOUD(levelname2);
            tests.db_del_lev(levelname);
            tests.db_del_lev(levelname2);
        }	
    }
}
